//
//  ZCSetUpViewController.m
//  VoiceMusic
//
//  Created by dllo on 15/10/16.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCSetUpViewController.h"
#import <Masonry.h>
#import "ZCSaveViewController.h"
#import "ZCAboutUsViewController.h"
#import <RESideMenu.h>
#import <UIImageView+WebCache.h>
#import "ZCAFNetWork.h"
#import "ZCDetailListModel.h"
#import "ZCPlayMusicTool.h"

@interface ZCSetUpViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) NSMutableArray *seArr;
@property (nonatomic, strong) UILabel *sizeLabel;
@property (nonatomic, strong) UISearchBar *search;
@property (nonatomic, strong) UITableView *searchTableView;
@property (nonatomic, strong) NSMutableArray *searchArr;
@property (nonatomic, copy) NSString *lastStr;
@end

@implementation ZCSetUpViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.arr = [NSMutableArray arrayWithObjects:@" ",@"我喜欢的歌曲",@"我的下载",@"清除缓存",@"关于我们", nil];
        self.seArr = [NSMutableArray arrayWithObjects:@"搜索",@"我的收藏",@"下载",@"缓存",@"系统设置", nil];
        self.searchArr = [NSMutableArray array];
    }
    return  self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"3187"]];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = YES;
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
        make.left.equalTo(self.view).offset(100);
    }];
    
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.searchTableView];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.bounces = YES;

    self.searchTableView.alpha = 0.8;
    self.searchTableView.hidden = YES;
    self.searchTableView.rowHeight = 50;
    self.searchTableView.backgroundColor = [UIColor whiteColor];
    
    [self.searchTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-200);
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(self.view).offset(160);
        make.left.equalTo(self.view).offset(110);
    }];
    
    
    //存放缓存大小的label;
    self.sizeLabel = [[ZCBaseLabel alloc] init];
    self.sizeLabel.font = [UIFont systemFontOfSize:15];
    // 搜索label
    self.search = [[UISearchBar alloc] init];
    self.search.placeholder = @"搜索歌曲";
    self.search.backgroundColor = [UIColor clearColor];
    self.search.layer.cornerRadius = 10;
    self.search.backgroundImage = [UIImage imageNamed:@"3187"];
    self.search.delegate = self;
    self.search.showsCancelButton = YES;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self creatData];
}
-(void)creatData{
    NSString *str = [self.search.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=1&size=50&app=ttpod&v=v8.0.1.2015091618&uid=&mid=iPhone7,2&f=f320&s=s310&imsi=&hid=&splus=9.0.1&active=1&net=2&openudid=e65d9a0e3de1aa2b70ba313f1ca52326ce8e2e06&idfa=5B302CA5-E537-4B10-955D-520F4C91BAFE&utdid=VeQF/rl/rPcDAJS/IF9m1eH3&alf=201200&bundle_id=com.ttpod.music&latitude=38.88260962951725&longtitude=121.5397083338999",str];
    
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        
        NSDictionary *dic = result;
        self.searchArr = [ZCDetailListModel baseModelByArr:dic[@"data"]];
        [self.searchTableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    self.searchTableView.hidden = YES;
    [self.search resignFirstResponder];
}



-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    self.searchTableView.hidden = NO;
    return YES;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self creatData];

    [self.search resignFirstResponder];
    if(self.searchArr.count != 0)return;
    self.searchTableView.hidden = YES;

    [searchBar resignFirstResponder];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == self.tableView){
        return 1;
    }else{
        return self.searchArr.count;
    }
   
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"re";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    if(tableView == self.tableView){
        cell.textLabel.text = self.arr[indexPath.section];
        if(indexPath.section == 3){
            self.sizeLabel.frame = CGRectMake(WIDTH - 170, 10 * HEIGHT / 677 , 80 * WIDTH / 375, 30 * HEIGHT / 677);
            [cell.contentView addSubview:self.sizeLabel];
            
            NSArray *cacheArr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,  NSUserDomainMask, YES);
            NSString *str = cacheArr[0];
            
            CGFloat f = [self folderSizeAtPath:str];
            NSString *Size = [NSString stringWithFormat:@"%0.1fM",f];
            self.sizeLabel.text = Size;
            
        }
        if(indexPath.section == 0){
            [cell.contentView addSubview:self.search];
            [self.search mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(cell.contentView).offset(5);
                make.bottom.equalTo(cell.contentView).offset(-5);
                make.left.equalTo(cell.contentView).offset(10);
                make.right.equalTo(cell.contentView).offset(-10);
            }];
        }
    }else{
        ZCDetailListModel *model = self.searchArr[indexPath.row];
        cell.textLabel.text = model.name;
        cell.detailTextLabel.text = model.singerName;
    
    }
    
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(tableView == self.tableView){
         return 5;
    }else{
        return 1;
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView) {
         return self.seArr[section];
    }else{
        return @"搜索结果";
    }
   
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        if(indexPath.section == 1){
            
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"nava" object:nil userInfo:dic];
            
            // 通知中心: 抽屉隐藏
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Hidden" object:nil];
            
            
        }else if (indexPath.section ==4)
        {
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"type",nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"nava" object:nil userInfo:dic];
            // 通知中心: 抽屉隐藏
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Hidden" object:nil];
            
        }else if (indexPath.section == 2){
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"nava" object:nil userInfo:dic];
            // 通知中心: 抽屉隐藏
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Hidden" object:nil];
            
        }else if (indexPath.section == 3){
            [self setAlter];
        }

    }else{
        
        //播放歌曲
        ZCDetailListModel *model = self.searchArr[indexPath.row];
        self.searchTableView.hidden = YES;
        [self.search resignFirstResponder];
        //    if(model.auditionList.count == 0) {
        //
        //        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"消息" message:@"版权不支持" preferredStyle:UIAlertControllerStyleAlert];
        //        [self presentViewController:alter animated:YES completion:nil];
        //
        //        [self dismissViewControllerAnimated:YES completion:^{
        //        }];
        //        return;
        //    }
        if(model.mvList.count == 0) {
            
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"消息" message:@"版权不支持" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alter animated:YES completion:nil];
            
            [self dismissViewControllerAnimated:YES completion:^{
            }];
            return;
        }
        
        //判断歌曲是否重复点击
        if([self.lastStr isEqualToString:model.auditionList[0][@"url"]])return;
        
        self.lastStr = model.auditionList[0][@"url"];
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:model.name,@"name",model.singerName,@"nameSinge",model.mvList[0][@"picUrl"],@"heat",model.auditionList[0][@"url"],@"url",nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:self userInfo:dic];
        
        [[NSUserDefaults standardUserDefaults] setObject:model.auditionList[0][@"url"] forKey:@"url"];
        //播放音乐
        [ZCPlayMusicTool getPlay:model.auditionList[0][@"url"]];
        [ZCPlayMusicTool sharePlay].urlMusic = model.auditionList[0][@"url"];
        //发送监听列表的属性
        NSDictionary *arrDic = [NSDictionary dictionaryWithObjectsAndKeys:self.searchArr,@"arr", nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"arr" object:nil userInfo:arrDic];
        
        [ZCPlayMusicTool sharePlay].pross = @"0";

    }
    
}

//计算缓存文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//清除缓存
- (CGFloat ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]){
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    
    CGFloat folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

//清除缓存的提示框
-(void)setAlter{
    
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"消息" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    //清除缓存的方法
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSArray *arr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,  NSUserDomainMask, YES);
        NSString *str =arr[0];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:str]) {
            NSArray *childerFiles=[manager subpathsAtPath:str];
            for (NSString *fileName in childerFiles) {
                //if([fileName isEqualToString:@"com.hackemist.SDWebImageCache.default"]){
                NSString *absolutePath = [str stringByAppendingPathComponent:fileName];
                [manager removeItemAtPath:absolutePath error:nil];
                //}
            }
        }
        [[SDImageCache sharedImageCache] cleanDisk];
        [self.tableView reloadData];
    }];
    
    [alter addAction:cancelAction];
    [alter addAction:otherAction];
    [self presentViewController:alter animated:YES completion:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
